// AI工具类 - DeepSeek AI聊天
const aiUtil = {
  // API基础URL
  baseUrl: 'http://localhost:8066',

  /**
   * 发送聊天消息（同步）
   */
  async chat(userId, message) {
    try {
      console.log('🤖 [aiUtil] 发送AI聊天请求:', { userId, message })

      const response = await wx.request({
        url: `${this.baseUrl}/ai/chat`,
        method: 'POST',
        header: {
          'content-type': 'application/json'
        },
        data: {
          userId,
          message
        },
        timeout: 60000 // 60秒超时
      })

      console.log('✅ [aiUtil] AI响应:', response.data)

      if (response.data.success) {
        return {
          success: true,
          response: response.data.response,
          timestamp: response.data.timestamp
        }
      } else {
        throw new Error(response.data.message || 'AI服务失败')
      }
    } catch (error) {
      console.error('❌ [aiUtil] AI聊天失败:', error)
      return {
        success: false,
        error: error.message || '网络错误，请稍后重试'
      }
    }
  },

  /**
   * 清空对话历史
   */
  async clearHistory(userId) {
    try {
      const response = await wx.request({
        url: `${this.baseUrl}/ai/history/clear`,
        method: 'POST',
        data: { userId }
      })

      return response.data
    } catch (error) {
      console.error('❌ [aiUtil] 清空历史失败:', error)
      return {
        success: false,
        error: error.message
      }
    }
  },

  /**
   * 健康检查
   */
  async healthCheck() {
    try {
      const response = await wx.request({
        url: `${this.baseUrl}/ai/health`,
        method: 'GET'
      })

      return response.data.status === 'ok'
    } catch (error) {
      console.error('❌ [aiUtil] 健康检查失败:', error)
      return false
    }
  }
}

module.exports = aiUtil

